import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Router, ActivatedRoute } from '@angular/router';
import { ReportUrls } from '../../comm/report.urls.conf';
import { Target } from '../../model/report/target';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { MachineFault } from '../../model/report/machine-fault';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';

declare const $: any;
import * as Enumerable from 'linq';
import { CommService } from '../../comm/comm.service';

@Component({
    selector: 'app-report-mf',
    templateUrl: './mf.component.html',
    styleUrls: ['./mf.component.css'],
})

export class MFComponent implements OnInit, AfterViewInit {
    title = '设备故障分析';
    showloading = true;
    public lineMtbf = 'mtbf';
    public lineMttr = 'mttr';
    public lineFT = '0';
    public mfList: MachineFault[];
    public mfChartsTFList: MachineFault[];
    public mfChartsMTTRList: MachineFault[];
    public mfChartsMTBFList: MachineFault[];
    public mfGroupList: MachineFault[];
    public chartMttrOption: any;
    public chartMtbfOption: any;
    public chartFaultTimeOption: any;
    public filterValue = 1;
    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public compareShiftItems: any[];
    public equipemntItems: TVResource[] = [];

    public subAareSelected: any;
    public equipmentSelected: TVResource[] = [];

    /*对比区域 - 班次*/
    public mfCompareList1: MachineFault[];
    public mfCompareList2: MachineFault[];
    public compareSubAareSelected: any;
    public compareEquipemntItems: TVResource[] = [];
    public compareEquipmentSelected: TVResource[] = [];
    public chartCompareMttrOption: any;
    public chartCompareMtbfOption: any;
    public chartCompareFaultTimeOption: any;
    public compareFilterValue = 1;
    public shiftSelected: any;
    public compareShiftSelected: any;

    /**目标值设置 */
    public yearItems: string[] = [];
    public yearMonthSelected: string;
    public yearWeekSelected: string;
    public targetItems: Target[];
    public weekTargetItems: Target[];
    public monthTargetItems: Target[];
    constructor(private commServices: CommService,
        public router: Router, public route: ActivatedRoute) {
    }
    // 组件初始化
    ngOnInit() {
        this.commServices.initDatePicker3($('#DateTimeRange'), 'YYYY-MM-DD');
        this.commServices.initDatePicker3($('#CompareDateTimeRange1'), 'YYYY-MM-DD');
        this.commServices.initDatePicker3($('#CompareDateTimeRange2'), 'YYYY-MM-DD');
        this.initYearValue();
        this.onYearChange('day', 1);
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAareSelected = this.subAreaItems[0];
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.compareShiftItems = this.commServices.shifts;
        this.compareShiftSelected = this.compareShiftItems[0];
        this.compareSubAareSelected = this.subAreaItems[0];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.compareEquipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.equipmentSelected = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.compareEquipmentSelected = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        // this.showCharts();

        this.filterValue = 1;
        this.route.queryParams.subscribe(params => {
            try {
                if (params['subAreas'] !== undefined && params['time'] !== undefined) {
                    // 根据时间段班次设置时间
                    this.setQueryTime('DateTimeRange', params['time']);
                    this.subAareSelected = this.subAreaItems.find(u => u.subArea === params['subAreas']);
                    this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAareSelected.subArea);
                    this.equipmentSelected = this.equipemntItems;
                    this.filterValue = Number.parseInt(params['filterValue']);
                    const shift = JSON.parse(params['shift']);
                    const a = this.shiftItems.find(e => e.shiftId === shift.shiftId);
                    this.shiftSelected = a;
                    debugger
                    this.getReportData();
                }
            } catch (error) {
                console.log(error.resultMessage);
            }
        });
        if (this.subAareSelected === undefined) {
            this.subAareSelected = this.subAreaItems[0];
            this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
            this.equipmentSelected = this.equipemntItems;
        }
    }

    setQueryTime(id: any, value: String) {
        $('#' + id).val(value);
    }

    onSubAreaSelectedChange(subArea: any): void {
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
        this.equipmentSelected = this.equipemntItems;
    }
    onCompareSubAreaSelectedChange(subArea: any): void {
        this.compareEquipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
        this.compareEquipmentSelected = this.compareEquipemntItems;
    }
    /**
     * 获取TimeRange的值
     * @param id id
     */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }
    ngAfterViewInit() {
    }

    /**获取表格数据*/
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        queryModel.filterValue = this.filterValue;
        queryModel.shift = this.shiftSelected.shiftId;
        this.commServices
            .getList(queryModel, ReportUrls.MFUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.mfList = model.data;
                    this.mfList.forEach(e => {
                        e.tfaultRate = Number.parseFloat(e.tfaultRate.toFixed(2));
                        e.mtbf = Number.parseFloat(e.mtbf.toFixed(2));
                        e.mttr = Number.parseFloat(e.mttr.toFixed(2));
                    });
                    this.mfChartsTFList = model.data;
                    this.mfChartsMTTRList = model.data;
                    this.mfChartsMTBFList = model.data;
                    this.showLineDatas();
                    this.showCharts();
                } else {
                    alert('获取数据失败,' + model.resultMessage);
                }
            });
    }
    onYearChange(year: string, targetType: number) {
        if (year !== '') {
            const target: Target = new Target();
            target.targetType = targetType;
            target.module = 'MachineFault';
            target.year = year;
            this.commServices
                .getList(target, ReportUrls.TargetUrl)
                .subscribe(model => {
                    if (model.resultCode === 200) {
                        if (targetType === 2) {
                            this.weekTargetItems = model.data;
                        } else if (targetType === 3) {
                            this.monthTargetItems = model.data;
                        } else {
                            this.targetItems = model.data;
                        }
                    } else {
                        alert('获取数据失败,' + model.resultMessage);
                    }
                });
        }
    }
    /**顶部三条数据展示 */
    showLineDatas() {
        this.lineMtbf = '';
        this.lineMttr = '';
        this.lineFT = '';
        Enumerable.from((this.mfList))
            .groupBy(e => e.subArea)
            .select(u => {
                this.lineMtbf = ((u.sum(item => item.tworkTime) - u.sum(item => item.tfaultTime)) / u.sum(e => e.tfaultCount)).toFixed(2);
                this.lineMttr = (u.sum(item => item.tfaultTime) / u.sum(item => item.tfaultCount)).toFixed(2);
                this.lineFT = ((u.sum(item => item.tfaultTime) / u.sum(item => item.tworkTime)) * 100).toFixed(2);
            }).toArray();
    }

    orderBy(type: any, orderByV: any) {
        if (type === 'tf') {
            if (orderByV === 'subArea') {
                this.mfChartsTFList = Enumerable.from(this.mfChartsTFList).orderBy(u => u.station).toArray();
            } else {
                this.mfChartsTFList = Enumerable.from(this.mfChartsTFList).orderByDescending(u => u.tfaultRate).toArray();
            }
        } else if (type === 'mttr') {
            if (orderByV === 'subArea') {
                this.mfChartsMTTRList = Enumerable.from(this.mfChartsMTTRList).orderBy(u => u.station).toArray();
            } else {
                this.mfChartsMTTRList = Enumerable.from(this.mfChartsMTTRList).orderByDescending(u => u.mttr).toArray();
            }
        } else if (type === 'mtbf') {
            if (orderByV === 'subArea') {
                this.mfChartsMTBFList = Enumerable.from(this.mfChartsMTBFList).orderBy(u => u.station).toArray();
            } else {
                this.mfChartsMTBFList = Enumerable.from(this.mfChartsMTBFList).orderBy(u => u.mtbf).toArray();
            }
        }
        this.showCharts();
    }



    /**展示报表图表*/
    showCharts(): void {
        const xtfData: Array<any> = [];
        const xmttrData: Array<any> = [];
        const xmtbfData: Array<any> = [];
        const yDataMttr: Array<any> = [];
        const yDataMtbf: Array<any> = [];
        const yDataFaultTime: Array<any> = [];
        const yMttr: Array<any> = [];
        const yMtbf: Array<any> = [];
        const yFt: Array<any> = [];

        const yMttrTargetData: Array<any> = [];
        const yMtbfTargetData: Array<any> = [];
        const ymcbfTargetData: Array<any> = [];
        const yFaultTimeTargetData: Array<any> = [];
        if (this.mfList !== undefined) {
            this.mfChartsTFList.forEach(e => {
                const station = e.station;
                xtfData.push(station);
                yFt.push(e.tfaultRate.toFixed(2));

                if (this.targetItems !== undefined) {
                    this.targetItems.map(el => {
                        if (el.targetName === 'MTTR') {
                            yMttrTargetData.push(el.targetValue);
                        } else if (el.targetName === 'MTBF') {
                            yMtbfTargetData.push(el.targetValue);
                        } else if (el.targetName === 'MCBF') {
                            ymcbfTargetData.push(el.targetValue);
                        } else {
                            yFaultTimeTargetData.push(el.targetValue);
                        }
                    });
                }

            });


            this.mfChartsMTTRList.forEach(e => {
                const station = e.station;
                xmttrData.push(station);
                yMttr.push(e.mttr.toFixed(2));
            });

            this.mfChartsMTBFList.forEach(e => {
                const station = e.station;
                xmtbfData.push(station);
                yMtbf.push(e.mtbf.toFixed(2));
            });

        }

        const mttrList = Enumerable.from(this.mfChartsMTTRList).orderByDescending(e => e.mttr).take(5).toArray();
        const pointMttr = new Array();
        mttrList.forEach(tf => {
            pointMttr.push({ name: '最高', value: tf.station, xAxis: tf.station, yAxis: tf.mttr });
        });
        const yBean = {
            name: 'MTTR',
            type: 'bar',
            data: yMttr,
            markPoint: {
                data: pointMttr
            }
        };

        const mtbfList = Enumerable.from(this.mfChartsMTBFList).orderBy(e => e.mtbf).where(e => e.mtbf !== 0).take(5).toArray();
        const pointMtbf = new Array();
        mtbfList.forEach(tf => {
            pointMtbf.push({ name: '最低', value: tf.station, xAxis: tf.station, yAxis: tf.mtbf });
        });
        const yBean1 = {
            name: 'MTBF',
            type: 'bar',
            data: yMtbf,
            markPoint: {
                data: pointMtbf
            }
        };

        const tfList = Enumerable.from(this.mfChartsTFList).orderByDescending(e => e.tfaultRate).take(5).toArray();
        const pointTF = new Array();
        tfList.forEach(tf => {
            pointTF.push({ name: '最高', value: tf.station, xAxis: tf.station, yAxis: tf.tfaultRate });
        });

        const yBeanFT = {
            name: '故障率',
            type: 'bar',
            data: yFt,
            markPoint: {
                data: pointTF
            }
        };
        yDataMttr.push(yBean);
        yDataMtbf.push(yBean1);
        yDataFaultTime.push(yBeanFT);

        const legendMttr = ['MTTR', '目标值'];
        const legendMtbf = ['MTBF', '目标值'];
        const legendFaultTime = ['故障率', '目标值'];
        this.chartMttrOption = ChartOptionCreater
            .createChartsOption('', '', '', '', legendMttr, xmttrData, yDataMttr, yMttrTargetData);//MTTR
        this.chartMtbfOption = ChartOptionCreater
            .createChartsOption('', '', '', '', legendMtbf, xmtbfData, yDataMtbf, yMtbfTargetData);//MTBF
        this.chartFaultTimeOption = ChartOptionCreater
            .createChartsOption('', '', '%', '', legendFaultTime, xtfData, yDataFaultTime, yFaultTimeTargetData);//故障率

    }
    /**获取对比数据*/
    showCompareCharts(): void {
        const queryModel = new QueryModel();
        queryModel.compareTimeRange1 = this.getTime('CompareDateTimeRange1');
        queryModel.compareTimeRange2 = this.getTime('CompareDateTimeRange2');
        queryModel.compareTypeValue = 1;
        queryModel.compareSubAreaIds = [this.compareSubAareSelected.subArea];
        queryModel.compareResourceIds = this.compareEquipmentSelected.map(e => e.resource);
        queryModel.filterValue = this.compareFilterValue;
        queryModel.shift = this.compareShiftSelected.shiftId;
        this.commServices.getList(queryModel, ReportUrls.MFCompareUrl).subscribe(model => {
            if (model.resultCode === 200) {
                this.mfCompareList1 = model.data.CompareList1;
                this.mfCompareList2 = model.data.CompareList2;
                this.showCompareChartsByData();
            } else {
                console.log(model.resultCode + ',' + model.resultMessage);
            }
        });
    }

    /**展示对比图表*/
    showCompareChartsByData(): void {

        const xData: Array<any> = [];
        const yDataMttr: Array<any> = [];
        const yDataMtbf: Array<any> = [];
        const yDataFaultTime: Array<any> = [];
        const yMttr: Array<any> = [];
        const yMtbf: Array<any> = [];
        const yFt: Array<any> = [];

        /*对比的线*/
        const yMttr1: Array<any> = [];
        const yMtbf1: Array<any> = [];
        const yFt1: Array<any> = [];

        const yMttrTargetData: Array<any> = [];
        const yMtbfTargetData: Array<any> = [];
        const yFaultTimeTargetData: Array<any> = [];
        const ymcbfTargetData: Array<any> = [];
        this.mfCompareList1.forEach(e => {
            const station = e.station;
            xData.push(station);
            yMttr.push(e.mttr.toFixed(2));
            yMtbf.push(e.mtbf.toFixed(2));
            yFt.push(e.tfaultRate.toFixed(2));
            this.targetItems.map(el => {
                if (el.targetName === 'MTTR') {
                    yMttrTargetData.push(el.targetValue);
                } else if (el.targetName === 'MTBF') {
                    yMtbfTargetData.push(el.targetValue);
                } else if (el.targetName === 'MCBF') {
                    ymcbfTargetData.push(el.targetValue);
                } else {
                    yFaultTimeTargetData.push(el.targetValue);
                }
            });
        });
        const yBean = {
            name: 'MTTR-1',
            type: 'line',
            data: yMttr
        };
        const yBean1 = {
            name: 'MTBF-1',
            type: 'line',
            data: yMtbf
        };
        const yBeanFT = {
            name: '故障率-1',
            type: 'line',
            data: yFt
        };
        yDataMttr.push(yBean);
        yDataMtbf.push(yBean1);
        yDataFaultTime.push(yBeanFT);

        this.mfCompareList2.forEach(e => {
            yMttr1.push(e.mttr.toFixed(2));
            yMtbf1.push(e.mtbf.toFixed(2));
            yFt1.push(e.tfaultRate.toFixed(2));
        });
        const yBean12 = {
            name: 'MTTR-2',
            type: 'line',
            data: yMttr1
        };
        const yBean2 = {
            name: 'MTBF-2',
            type: 'line',
            data: yMtbf1
        };
        const yBeanFT2 = {
            name: '故障率-2',
            type: 'line',
            data: yFt1
        };
        yDataMttr.push(yBean12);
        yDataMtbf.push(yBean2);
        yDataFaultTime.push(yBeanFT2);
        const legendMttr = ['MTTR-1', 'MTTR-2', '目标值'];
        const legendMtbf = ['MTBF-1', 'MTBF-2', '目标值'];
        const legendFaultTime = ['故障率-1', '故障率-2', '目标值'];
        this.chartCompareMttrOption = ChartOptionCreater.createChartsOption('', '', '', '', legendMttr,
            xData, yDataMttr, yMttrTargetData); //对比图表-MTTR
        this.chartCompareMtbfOption = ChartOptionCreater.createChartsOption('', '', '', '', legendMtbf,
            xData, yDataMtbf, yMtbfTargetData); //对比图表-MTBF
        this.chartCompareFaultTimeOption = ChartOptionCreater.createChartsOption('', '', '%', '', legendFaultTime,
            xData, yDataFaultTime, yFaultTimeTargetData);//对比图表-故障率
    }

    /**ECharts图表相关*/
    chartsMap = new Map<String, any>();
    onChartInit(index: String, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        if (index !== '-MTBF-' && index !== '-设备故障率-' && index !== '-MTTR-') {
            echartsIntance.on('click', (params: any) => {
                const equipment = params.name;
                const resource = this.equipemntItems
                    .find(e => e.equipment === equipment);
                this.gotoDetail(resource);
            });
        }
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe(() => this.chartsMap.forEach((v) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }

    selectedCompareIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex + 3).resize();
    }

    /**点击对应的图表进入详情界面 */
    gotoDetail(resource: TVResource): void {
        const p = {
            'time': this.getTime('DateTimeRange'),
            'subAreas': this.subAareSelected.subArea,
            'resources': resource.resource,
            'shift': JSON.stringify(this.shiftSelected),
            'filterValue': this.filterValue
        };
        this.router.navigate(['/ptpmc/report/mfa'], {
            queryParams: p
        });
    }

    /**初始化设置的图表目标值 */
    public initYearValue(): void {
        this.commServices.getList(null, ReportUrls.TargetYearUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.yearItems = model.data;
                    const dt: Date = new Date();
                    this.yearMonthSelected = dt.getFullYear().toString();
                    this.yearWeekSelected = dt.getFullYear().toString();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    /**对页面数据进行导出 */
    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAareSelected.subArea);
        let resourceStr = '';
        this.equipmentSelected.map(e => e.equipment).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        queryModelArray.push('过滤值:' + this.filterValue + '分钟');
        this.chartsMap.forEach((v, k) => {
            if (k !== '-MTBF-' && k !== '-设备故障率-' && k !== '-MTTR-') {
                const picBase64Info = v.getDataURL();
                files.push({
                    chartsTitle: k, chartsEncodeStr: picBase64Info
                });
            }
        });

        this.commServices.exportPdf({
            extraMessage: ['MTTR:' + this.lineMttr, 'MTBF:' + this.lineMtbf, '平均故障率:' + this.lineFT + '%'],
            reportTitle: this.title, charts: files, queryModel: queryModelArray
        });
    }

    protected exportCompareData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();

        queryModelArray.push('对比时间1:' + this.getTime('CompareDateTimeRange1'));
        queryModelArray.push('对比时间2:' + this.getTime('CompareDateTimeRange2'));
        queryModelArray.push('区域:' + this.compareSubAareSelected.subArea);
        let resourceStr = '';
        this.compareEquipmentSelected.map(e => e.equipment).forEach(e => {
            resourceStr += e + ',';
        });
        queryModelArray.push('设备:' + resourceStr);
        queryModelArray.push('班次:' + (this.compareShiftSelected.shiftId === '-1' ? '全部'
            : this.compareShiftSelected.shiftId === '1' ? '早班' : '中班'));
        queryModelArray.push('过滤值:' + this.compareFilterValue + '分钟');
        this.chartsMap.forEach((v, k) => {
            if (k === '-MTBF-' || k === '-设备故障率-' || k === '-MTTR-') {
                const picBase64Info = v.getDataURL();
                files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
            }
        });

        this.commServices.exportPdf({
            reportTitle: this.title, charts: files, queryModel: queryModelArray
        });
    }

    public updateTargetList: Target[] = [];
    updateTarget(e) {
        let index: number = this.updateTargetList.findIndex(u => u.id === e.key.id)
        if (index !== -1) {
            this.updateTargetList[index] = e.key;
        } else {
            this.updateTargetList.push(e.key)
        }
    }
    saveTargetChange() {
        this.commServices.update(this.updateTargetList, ReportUrls.TargetUpdateUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.updateTargetList = [];
                    this.commServices.showNotification('更新成功', 'success');
                    this.getReportData();
                } else {
                    this.commServices.showNotification('更新数据失败,' + model.resultMessage, 'warning');
                }
            });
    }
    onCellPrepared(e) {
        if (e.rowType === 'data' && e.column.command === 'edit') {
            const isEditing = e.row.isEditing,
                cellElement = e.cellElement;
            if (isEditing) {
                const saveLink = cellElement.querySelector('.dx-link-save'),
                    cancelLink = cellElement.querySelector('.dx-link-cancel');

                saveLink.classList.add('dx-icon-save');
                cancelLink.classList.add('dx-icon-revert');

                saveLink.textContent = '';
                cancelLink.textContent = '';
            } else {
                const editLink = cellElement.querySelector('.dx-link-edit'),
                    deleteLink = cellElement.querySelector('.dx-link-delete');

                editLink.classList.add('dx-icon-edit');
                deleteLink.classList.add('dx-icon-trash');

                editLink.textContent = '';
                deleteLink.textContent = '';
            }
        }
    }

    @ViewChild('dddb') dddb: DxDropDownBoxComponent;
    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }
    @ViewChild('dddbCompare') dddbCompare: DxDropDownBoxComponent
    clearCompareEquipmentSelected() {
        this.compareEquipmentSelected = [];
    }
    compareEquipmentSelectedOk() {
        this.dddbCompare.instance.close();
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
